<template>
  <el-form
    ref="login"
    v-loading.fullscreen.lock="fullscreenLoading"
    :model="login"
    :rules="rules"
    class="login-form"
    size="medium"
    v-bind="$attrs"
  >
    <h3 class="title">
      <!-- <span>登录</span>
      <span>SIGN IN</span> -->
      <span>智美医经营管理后台系统</span>
    </h3>
    <el-form-item>
      <el-switch
        v-model="value"
        style="display: block"
        active-color="#13ce66"
        inactive-color="#1890FF"
        active-text="后台登录"
        inactive-text="医院登录"
        @change="onChange"
      />
    </el-form-item>
    <el-form-item prop="username">
      <el-input v-model="login.username" type="text" auto-complete="off" placeholder="请输入账号"> -->
        <span slot="prefix">
          <svg-icon class="login-icon" icon-class="user" />
        </span>
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input
        v-model="login.password"
        :type="passShow ? 'text' : 'password'"
        auto-complete="off"
        placeholder="请输入密码"
        @keyup.enter.native="handleLogin"
      >
        <span slot="prefix">
          <svg-icon class="login-icon" icon-class="lock" />
        </span>
        <span slot="suffix" class="check-pass" @click="handleCheckPass">
          <svg-icon class="login-icon" :icon-class="passShow ? 'yanjing_kai' : 'yanjing_bi'" />
        </span>
      </el-input>
    </el-form-item>

    <!-- 验证码 -->
    <el-form-item prop="captcha" class="login-code-box">
      <el-input v-model="login.captcha" auto-complete="off" placeholder="请输入验证码" @keyup.enter.native="handleLogin">
        <span slot="prefix">
          <svg-icon class="login-icon" icon-class="safetycertificate" />
        </span>
      </el-input>
      <div class="login-code">
        <img v-if="!!codeUrl" :src="codeUrl" @click="imgClick">
      </div>
    </el-form-item>

    <!-- 选择平台 -->
    <el-form-item v-if="hasPlatform && value" prop="appId">
      <el-select v-model="login.appId" placeholder="请选择平台" style="width:100%;">
        <el-option v-for="(item,index) in platform" :key="index" :label="item.fullName" :value="item.id" />
        <span slot="prefix">
          <svg-icon class="login-icon" icon-class="appstore" />
        </span>
      </el-select>
    </el-form-item>

    <!-- 选择医院-->
    <el-form-item v-if="!value" prop="hospital">
      <!-- <el-select v-model="login.appId" placeholder="请选择医院" style="width:100%;">
        <el-option v-for="(item,index) in platform" :key="index" :label="item.fullName" :value="item.id" />
        <span slot="prefix">
          <svg-icon class="login-icon" icon-class="appstore" />
        </span>
      </el-select> -->
      <el-select v-model="login.hospitalId" filterable placeholder="请选择医院" @change="hospitalChange">
        <el-option v-for="item in hospitalList" :key="item.id" :label="item.hospitalName" :value="item.id" />
      </el-select>
    </el-form-item>

    <!-- 记住密码 -->
    <el-row>
      <el-col :span="24">
        <el-checkbox v-model="rememberMe" style="margin:0 0 24px 0;">记住密码</el-checkbox>
      </el-col>
    </el-row>

    <el-form-item style="width:100%;">
      <el-button class="submit-login-btn" :loading="loading" type="primary" @click.native.prevent="handleLogin">
        <span v-if="!loading">登 录</span>
        <span v-else>登 录 中...</span>
      </el-button>
    </el-form-item>

    <!-- <div class="other-login">
      <div class="login-platform-wrapper">
        <div class="login-platform-item">
          <div class="icon wechat" />
          <div class="name">微信登录</div>
        </div>
        <div class="login-platform-item" @click="handleDDLogin()">
          <div class="icon dingding" />
          <div class="name">钉钉登录</div>
        </div>
      </div>
    </div> -->
    <!--    <DingdingLogin-->
    <!--      :dd-visible="ddVisible"-->
    <!--      :set-fullscreen-loading="setFullscreenLoading"-->
    <!--      :set-app-id="this.$parent.setAppId"-->
    <!--      :set-dd-visible="setDdVisible"-->
    <!--    />-->
    <slot />
  </el-form>
</template>
<script>
// eslint-disable-next-line no-unused-vars
import {
  SvgIcon,
  requestNoToken,
  encrypt,
  setAppId,
  // setToken,
  setHisId,
  removeHisId,
  setHisToken,
  removeHisToken,
  setLocalStorage,
} from "@monkey.do/monkey";
import { sm2Encrypt } from '@/utils/utils';
import Cookies from 'js-cookie';
import "@assets/styles/login.scss";
// eslint-disable-next-line no-unused-vars
import user from "@assets/icons/svg/user.svg";
import "@assets/icons/svg/lock.svg";
import "@assets/icons/svg/yanjing_bi.svg";
import "@assets/icons/svg/yanjing_kai.svg";
import "@assets/icons/svg/password.svg";
import "@assets/icons/svg/safetycertificate.svg";
import "@assets/icons/svg/appstore.svg";
// import DingdingLogin from "@rabbit/components/OtherLogin/DingdingLogin";
export default {
  name: "LoginForm",
  // components: { SvgIcon, DingdingLogin },
  components: { SvgIcon },
  props: {
    title: {
      type: String,
      default: "",
    },
    initialValue: {
      type: Object,
      default: () => ({}),
    },
    codePath: {
      type: String,
      default: "",
    },
    hasPlatform: {
      type: Boolean,
      default: true,
    },
    onConfirm: {
      type: Function,
      default: () => {
        return new Promise((resolve) => {
          resolve();
        });
      },
    },
    isRemember: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      login: this.initialValue,
      codeUrl: "",
      cookiePassword: "",
      value: false,
      redirect: undefined,
      rules: {
        username: [
          { required: true, trigger: "blur", message: "用户名不能为空" },
        ],
        password: [
          { required: true, trigger: "blur", message: "密码不能为空" },
        ],
        captcha: [
          { required: true, trigger: "change", message: "验证码不能为空" },
        ],
        hospitalId: [
          { required: true, trigger: "change", message: "请选择医院" },
        ],
        platform: [
          {
            required: this.hasPlatform,
            trigger: "change",
            message: "请选择平台",
          },
        ],
      },
      platform: [],
      loading: false,
      passShow: false,
      ddVisible: false,
      appId: "",
      fullscreenLoading: false,
      hospitalList: [],
      cities: [{
        value: 1,
        label: '8:00~9:00',
        flag: true,
      }, {
        value: 2,
        label: '9:00~10:00',
        flag: false,
      }, {
        value: 3,
        label: '10:00~11:00',
        flag: true,
      }, {
        value: 4,
        label: '11:00~12:00',
        flag: false,
      }],
      values: "",
      hospitalName: "",
    };
  },
  computed: {
    rememberMe: {
      get() {
        return this.isRemember;
      },
      set(value) {
        this.$emit("update:isRemember", value);
      },
    },
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true,
    },
  },
  mounted() {
    // this.getCode();
    this.captcha();
    this.getPlatform();
    this.onChange(this.value);
    this.getAllHospital();
    removeHisId();
    removeHisToken();
  },
  methods: {
    setFullscreenLoading(value) {
      this.fullscreenLoading = value;
    },
    setDdVisible() {
      this.ddVisible = false;
    },
    handleLogin() {
      this.$refs.login.validate(async(valid) => {
        if (valid) {
          this.loading = true;
          const password = encrypt(this.login.password);
          if (this.value) {
            this.onConfirm({ ...this.login, password })
              .then((res) => {
                if (res.statusCode !== 600) this.getCode();
              })
              .finally(() => {
                this.loading = false;
              });
          } else {
            this.setCookie(this.login);
            this.login.account = this.login.username;
            const password = sm2Encrypt(this.login.password);
            const res = await this.$api["data/hospitalStaff/login"]({ ...this.login, passwd: password });
            this.loading = false;
            if (res.code !== 200) {
              this.$message.error(res.msg);
              this.captcha();
              return;
            }
            setAppId(this.login["hospitalId"]);
            setHisToken(res.data.token);
            setHisId(this.login["hospitalId"]);
            localStorage.hospitalName = this.hospitalName;
            this.loadWareHouse();
            this.loadHisUsr();
            this.$router.push({ path: this.redirect || '/' });
          }
        }
      });
    },
    loadWareHouse() {
      // 导入库房做本地缓存
      this.$api['data/storehouse/list']({ page: 1, pageSize: 99999, query: { status: "启用" }}).then(res => {
        if (res.code !== 200) return;
        setLocalStorage("WARE_HOUSE", res.data.result);
      });
    },
    loadHisUsr() {
      // 拉取当前登陆医院的所有医院用户
      this.$api['doctor/consulting/getAllUsr']().then(resData => {
        if (resData.data) {
          setLocalStorage("HIS_USR_LIST", resData.data);
        }
      })
        .catch(err => {
          console.error(err);
          this.$message.error('拉取医院用户失败');
        });
    },
    setCookie(value) {
      if (this.rememberMe) {
        Cookies.set('username', value.username, { expires: 30 });
        Cookies.set('password', value.password, { expires: 30 });
        // Cookies.set('rememberMe', this.rememberMe, { expires: 30 });
        Cookies.set('hospitalId', value.hospitalId, { expires: 30 });
      } else {
        Cookies.remove('username');
        Cookies.remove('password');
        Cookies.remove('rememberMe');
      }
    },
    async getAllHospital() {
      const res = await this.$api["data/hospital/hospitalList"]({ page: 1, pageSize: 99999 });
      if (res.code !== 200) return;
      this.hospitalList = res.data.result;
    },
    handleDDLogin() {
      this.ddVisible = true;
    },
    handleCheckPass() {
      this.passShow = !this.passShow;
    },
    getCode() {
      requestNoToken({
        // eslint-disable-next-line
        baseURL: GLOBAL.RABBIT_SERVER,
        url: "/rabbit/captcha/get",
        method: "get",
      }).then((res) => {
        if (res.statusCode === 600) {
          this.codeUrl = "data:image/gif;base64," + res.data.image;
          this.login.uuid = res.data.uuid;
        }
      });
    },
    getPlatform() {
      if (this.hasPlatform) {
        // eslint-disable-next-line
        requestNoToken({baseURL: GLOBAL.RABBIT_SERVER, url: "/rabbit/login/get/app/list"}).then(
          (res) => {
            if (res.statusCode === 600) {
              this.platform = res.data;
            }
          }
        );
      }
    },
    onChange(val) {
      removeHisId();
      removeHisToken();
      this.login.uuid = "";
      if (val) {
        this.login.appId = "4101";
        this.getCode();
      } else {
        this.captcha();
      }
    },
    async captcha() {
      let reqId = "";
      if (!this.value && this.login.uuid) {
        reqId = this.login.uuid;
      }
      const res = await this.$api["data/hospitalStaff/captcha"]({ reqId: reqId });
      if (res.code !== 200) {
        this.$message.error("验证码获取错误，请刷新重试或联系管理员");
        return;
      }
      this.codeUrl = "data:image/gif;base64," + res.data.image;
      this.login.uuid = res.data.uuid;
    },
    imgClick() {
      if (this.value) {
        this.getCode();
      } else {
        this.captcha();
      }
    },
    hospitalChange(id) {
      console.log(id);
      this.hospitalList.forEach(item => {
        if (item.id === id) {
          this.hospitalName = item.hospitalName;
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.login-form .title > span:first-child {
  // border-right: none !important;
  border-right-width: 0px;
}

input {
  border-width: 0px !important;
}

.login-form .submit-login-btn {
  width: 100%;
}
</style>
